package com.kcs.fxmargin.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;

import org.apache.log4j.Logger;

import com.kcs.common.utils.Constant;
import com.kcs.common.utils.commonUtils;
import com.kcs.fxmargin.model.TRateDetail;

public class TRateDetailDAO {
	private Logger log = Logger.getLogger(Constant.LOG_FX);
	
	public int insert(List<TRateDetail> modelList, Connection conn)throws Exception{
		PreparedStatement pstmt = null;
		StringBuffer sql = new StringBuffer();
		int res = -1;		
		try{
			sql.append(" insert into t_rate_detail ");
			sql.append("  ( id,rate_header_id,curr1,curr2,period, ");
			sql.append("    rate,day_count,active_status,create_by, ");
			sql.append("    create_dt, row_version ) ");
			sql.append(" values (?, ?, ?, ?, ?, ?, ?, ?, ?, getdate(), ?) ");
		
			if(commonUtils.isNotEmpty(modelList)){
				pstmt = conn.prepareStatement(sql.toString());
				
				for(int i=0;i<modelList.size();i++){
					
					TRateDetail model = modelList.get(i);					
					int ind = 1;	
					
					pstmt.setString(ind++, model.getId());
					pstmt.setString(ind++, model.getRateHeaderId());
					pstmt.setString(ind++, model.getCurr1());
					pstmt.setString(ind++, model.getCurr2());

					pstmt.setString(ind++, model.getPeriod());
					pstmt.setBigDecimal(ind++, model.getRate());
					pstmt.setInt(ind++, model.getDayCount());
					pstmt.setString(ind++, model.getActiveStatus());
					pstmt.setString(ind++, model.getCreateBy());
					pstmt.setInt(ind++, model.getRowVersion());
										
					pstmt.addBatch();
				}

				int[] exBatch = pstmt.executeBatch();
				
				System.out.println("exBatch="+exBatch.length);
				System.out.println("modelList.size()="+modelList.size());
				//if(exBatch!=null){
				  if(exBatch.length == modelList.size()){				
					res = 1;
				  }
				//}
				
			}
			
		}catch(Exception e){
			log.error(e.getMessage());
			res = -1;
			throw e;
		}finally{
			if(pstmt != null){
				try{
					pstmt.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
		
		return res;
	}
		
	
	public int delete(TRateDetail model, Connection conn)throws Exception{
		PreparedStatement pstmt = null;
		StringBuffer sql = new StringBuffer();
		int res = -1;
		
		try{
			sql.append(" delete from t_rate_detail ");
			sql.append(" where rate_header_id = ? ");
			pstmt = conn.prepareStatement(sql.toString());
			
			int i =1;
			pstmt.setString(i++, model.getRateHeaderId());
			
			res = pstmt.executeUpdate();
			
		}catch(Exception e){
			log.error(e.getMessage());
			throw e;
		}finally{
			if(pstmt != null){
				try{
					pstmt.close();
				}catch(Exception ex){
					throw ex;
				}
			}
		}
		
		return res;
	}
	
	
}

